<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class PhoneLoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm()
    {
        return view('auth.phone-login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'phone' => 'required|regex:/^1[3-9]\d{9}$/',
        ]);

        $user = User::firstOrCreate(
            ['phone' => $request->phone],
            [
                'name' => '用户' . substr($request->phone, -4),
                'password' => Hash::make(Str::random(32)),
            ]
        );

        Auth::login($user);

        return redirect()->intended(route('assignments.index'));
    }

    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}
